﻿using MQTTnet.Client.Receiving;
using MQTTnet.Protocol;
using MQTTnet.Server;
using MQTTnet;
using System;
using System.Diagnostics.Tracing;
using System.Net;
using System.Text;


namespace Mqttserver
{
    internal class Program
    {
        public static IMqttServer? mqttServer;
        static void Main(string[] args)
        {
            Task.Run(() => Start());
            Console.ForegroundColor = ConsoleColor.Red;
            Console.WriteLine("服务端目前充当消息转发媒介，" +
    "可以向指定订阅的客户端发送消息，\n" +
    "但不建议直接从服务端面板发送，" +
    "推荐使用跨平台的客户端进行操控交互");
            while (true)
            {
 
                Console.ForegroundColor = ConsoleColor.Green;
                Console.WriteLine("==========================================");
                var cmmd = Console.ReadLine();

                switch (cmmd)
                {
                    case "qt":
                        stop();
                        break;                     
                    default:
                        Console.WriteLine("主题数据名字:");
                        var cmd = Console.ReadLine();
                        Console.WriteLine("内容:");
                        var cmdr = Console.ReadLine();
                        if (mqttServer != null)
                        {
                            Sendmesage(cmd, cmdr);
                        }
                        break;
                }
   

            }

        }

        /// <summary>
        /// 启动mqtt服务器
        /// </summary>
        private async static void Start()
        {
            // 创建MQTT服务器选项
            IMqttServerOptions? mqttServerOptions = new MqttServerOptionsBuilder()
                .WithDefaultEndpointPort(1883) // 设置MQTT服务器端口
                .Build();

            // 创建MQTT服务器
             mqttServer = new MqttFactory().CreateMqttServer();

            // 处理客户端连接事件
            mqttServer.ClientConnectedHandler = new MqttServerClientConnectedHandlerDelegate(e =>
            {
                Console.WriteLine($"客户端连接: {e.ClientId}");
            });

            // 处理客户端断开连接事件
            mqttServer.ClientDisconnectedHandler = new MqttServerClientDisconnectedHandlerDelegate(e =>
            {
                Console.WriteLine($"客户端断开连接: {e.ClientId}");
            });

            // 处理消息接收事件
            mqttServer.ApplicationMessageReceivedHandler = new MqttApplicationMessageReceivedHandlerDelegate(e =>
            {
                var message = Encoding.UTF8.GetString(e.ApplicationMessage.Payload);
                Console.WriteLine($"接收到消息: 主题={e.ApplicationMessage.Topic}, 消息={message}");
            });


            // 启动MQTT服务器
            await mqttServer.StartAsync(mqttServerOptions);
            Console.WriteLine($"MQTT服务器已启动 {mqttServerOptions.DefaultEndpointOptions.BoundInterNetworkAddress}:{mqttServerOptions.DefaultEndpointOptions.Port}");
        }

        /// <summary>
        /// 消息发送
        /// </summary>
        /// <param name="topic"></param>
        /// <param name="messg"></param>
        public async static void Sendmesage(string topic, string messg) 
        {
                // 创建MQTT消息
                var mqttMessage = new MqttApplicationMessageBuilder()
                    .WithTopic(topic)
                    .WithPayload(messg)
                    .WithQualityOfServiceLevel(MqttQualityOfServiceLevel.AtLeastOnce)
                    .Build();
                // 发布消息
                await mqttServer.PublishAsync(mqttMessage);
                Console.WriteLine("消息已发送");
          
        }

        /// <summary>
        /// 停止服务器
        /// </summary>
        public async static void stop() 
        {
            if (mqttServer!=null)
            {
                await mqttServer.StopAsync();
                Console.WriteLine("MQTT服务器已停止");
            }
 
        }

    }

}
